package com.campus.help.service;

import com.campus.help.dto.UserLoginRequest;
import com.campus.help.dto.UserRegisterRequest;
import com.campus.help.entity.User;
import com.campus.help.repository.UserRepository;
import com.campus.help.util.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    /**
     * 用户注册
     * @param request 注册请求
     * @return 注册结果
     */
    public String register(UserRegisterRequest request) {
        // 检查学号是否已存在
        if (userRepository.existsByStudentId(request.getStudentId())) {
            throw new RuntimeException("学号已存在");
        }
        
        // 创建用户
        User user = new User();
        user.setStudentId(request.getStudentId());
        user.setPassword(SecurityUtil.encryptPassword(request.getPassword()));
        user.setName(request.getName());
        user.setPhone(request.getPhone());
        user.setEmail(request.getEmail());
        
        userRepository.save(user);
        return "注册成功";
    }
    
    /**
     * 用户登录
     * @param request 登录请求
     * @return 登录结果
     */
    public String login(UserLoginRequest request) {
        Optional<User> userOpt = userRepository.findByStudentId(request.getStudentId());
        
        if (!userOpt.isPresent()) {
            throw new RuntimeException("用户不存在");
        }
        
        User user = userOpt.get();
        if (!SecurityUtil.verifyPassword(request.getPassword(), user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        
        return "登录成功";
    }
    
    /**
     * 根据学号查找用户
     * @param studentId 学号
     * @return 用户信息
     */
    public Optional<User> findByStudentId(String studentId) {
        return userRepository.findByStudentId(studentId);
    }
    
    /**
     * 验证用户是否存在
     * @param studentId 学号
     * @return 是否存在
     */
    public boolean existsByStudentId(String studentId) {
        return userRepository.existsByStudentId(studentId);
    }

    public User save(User user) {
        return userRepository.save(user);
    }
}